/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.manage.biuserapplication.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.core.dbs.CurrentDataSourceContext;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.common.WdAnalysisConst;
import vip.xiaonuo.modular.manage.biapplication.entity.BiApplication;
import vip.xiaonuo.modular.manage.biapplication.param.BiApplicationParam;
import vip.xiaonuo.modular.manage.biapplication.service.BiApplicationService;
import vip.xiaonuo.modular.manage.bicouponwrite.mapper.BiCouponWriteMapper;
import vip.xiaonuo.modular.manage.biuserapplication.entity.BiUserApplication;
import vip.xiaonuo.modular.manage.biuserapplication.enums.BiUserApplicationExceptionEnum;
import vip.xiaonuo.modular.manage.biuserapplication.mapper.BiUserApplicationMapper;
import vip.xiaonuo.modular.manage.biuserapplication.param.BiUserApplicationParam;
import vip.xiaonuo.modular.manage.biuserapplication.service.BiUserApplicationService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户应用service接口实现类
 *
 * @author zj
 * @date 2022-08-09 11:43:02
 */
@Service
public class BiUserApplicationServiceImpl extends ServiceImpl<BiUserApplicationMapper, BiUserApplication> implements BiUserApplicationService {


    @Resource
    private BiApplicationService biApplicationService;

    @Resource
    private BiCouponWriteMapper biCouponWriteMapper;


    @Override
    public PageResult<BiUserApplication> page(BiUserApplicationParam biUserApplicationParam) {
        QueryWrapper<BiUserApplication> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(biUserApplicationParam)) {

            // 根据用户id 查询
            if (ObjectUtil.isNotEmpty(biUserApplicationParam.getUserId())) {
                queryWrapper.lambda().eq(BiUserApplication::getUserId, biUserApplicationParam.getUserId());
            }
            // 根据应用id 查询
            if (ObjectUtil.isNotEmpty(biUserApplicationParam.getApplicationId())) {
                queryWrapper.lambda().eq(BiUserApplication::getApplicationId, biUserApplicationParam.getApplicationId());
            }
            // 根据启用/停用 Y/N 查询
            if (ObjectUtil.isNotEmpty(biUserApplicationParam.getIsenable())) {
                queryWrapper.lambda().eq(BiUserApplication::getIsenable, biUserApplicationParam.getIsenable());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<BiUserApplication> list(BiUserApplicationParam biUserApplicationParam) {
        return this.list();
    }

    @Override
    public void add(BiUserApplicationParam biUserApplicationParam) {
        BiUserApplication biUserApplication = new BiUserApplication();
        BeanUtil.copyProperties(biUserApplicationParam, biUserApplication);
        this.save(biUserApplication);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BiUserApplicationParam> biUserApplicationParamList) {
        biUserApplicationParamList.forEach(biUserApplicationParam -> {
            this.removeById(biUserApplicationParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BiUserApplicationParam biUserApplicationParam) {
        BiUserApplication biUserApplication = this.queryBiUserApplication(biUserApplicationParam);
        BeanUtil.copyProperties(biUserApplicationParam, biUserApplication);
        this.updateById(biUserApplication);
    }

    @Override
    public BiUserApplication detail(BiUserApplicationParam biUserApplicationParam) {
        return this.queryBiUserApplication(biUserApplicationParam);
    }

    /**
     * 获取用户应用
     *
     * @author zj
     * @date 2022-08-09 11:43:02
     */
    private BiUserApplication queryBiUserApplication(BiUserApplicationParam biUserApplicationParam) {
        BiUserApplication biUserApplication = this.getById(biUserApplicationParam.getId());
        if (ObjectUtil.isNull(biUserApplication)) {
            throw new ServiceException(BiUserApplicationExceptionEnum.NOT_EXIST);
        }
        return biUserApplication;
    }

    @Override
    public void export(BiUserApplicationParam biUserApplicationParam) {
        List<BiUserApplication> list = this.list(biUserApplicationParam);
        PoiUtil.exportExcelWithStream("SnowyBiUserApplication.xls", BiUserApplication.class, list);
    }

    @Override
    public List<BiApplication> findByUserId(Long id,String name) {
        LambdaQueryWrapper<BiApplication> appWrapper = new LambdaQueryWrapper<>();
        appWrapper.eq(BiApplication::getIsEnable, "Y");
        if (StringUtils.isNotEmpty(name)) {
            appWrapper.like(BiApplication::getName, name);
        }
        List<BiApplication> biApplications = biApplicationService.list(appWrapper);
        for (BiApplication app : biApplications) {
            QueryWrapper<BiUserApplication> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(BiUserApplication::getUserId,id);
            queryWrapper.lambda().eq(BiUserApplication::getApplicationId, app.getId());
            queryWrapper.lambda().last(" limit 1 ");
            BiUserApplication one = this.getOne(queryWrapper);
            if (one != null) {
                app.setUserApplicationId(one.getId());
                app.setIsEnable(one.getIsenable());
            }else{
                app.setIsEnable("N");
            }
            //如果是茶百道，则查询优惠券，客流量，客单价菜单
            if (app.getOrgCode().equals("chabaidao")) {
                List<BiApplication> children = new ArrayList<>();
                //券种类
                BiApplication coupon = new BiApplication();
                coupon.setName("优惠券核销量");
                coupon.setOrgCode(app.getOrgCode()+"_coupon");
                CurrentDataSourceContext.setDataSourceType(WdAnalysisConst.CLICKHOUSE_DATASOURCE);
                List<String> couponNameList = biCouponWriteMapper.queryCouponNameList(app.getOrgCode());
                CurrentDataSourceContext.clearDataSourceType();
                List<BiApplication> couponChildren = new ArrayList<>();
                for (String str : couponNameList) {
                    BiApplication c = new BiApplication();
                    c.setName(str);
                    c.setOrgCode(app.getOrgCode()+"_coupon_"+str);
                    couponChildren.add(c);
                }
                coupon.setChildren(couponChildren);
                children.add(coupon);
                //客流量
                BiApplication passengerFlow = new BiApplication();
                passengerFlow.setName("客流量");
                passengerFlow.setOrgCode(app.getOrgCode()+"_passengerFlow");
                children.add(passengerFlow);
                //客单价
                BiApplication passengerPrice = new BiApplication();
                passengerPrice.setName("客单价");
                passengerPrice.setOrgCode(app.getOrgCode()+"_passengerPrice");
                children.add(passengerPrice);
                app.setChildren(children);
            }

        }
        return biApplications;
    }

    @Override
    public void updateisEnable(BiApplicationParam biApplicationParam) {
        BiUserApplication one = this.getById(biApplicationParam.getUserApplicationId());
        if (one != null) {
           one.setIsenable("Y".equals(one.getIsenable())?"N":"Y");
            this.updateById(one);
        }
    }
}
